package http

import (
	"awesomeTask/system/helper"
	"io/ioutil"
	"net/http"
	"strings"
)

type HttpClient struct {
	requestUrl    string
	requestHeader map[string]interface{}
	requestData   map[string]interface{}
	getParams     map[string]string
	requestMothod string
}

func (client *HttpClient) SetGetParams(key string, value string) *HttpClient {
	client.init()
	client.getParams[key] = value
	return client
}
func (client *HttpClient) SetHeader(key string, value string) *HttpClient {
	client.init()
	client.requestHeader[key] = value
	return client
}
func (client *HttpClient) Get(url string) (string, error) {
	client.requestMothod = "GET"
	url += "?"
	for key, value := range client.getParams {
		url += key + "=" + value + "&"
	}
	url = url[0 : len(url)-1]
	client.requestUrl = url
	return client.request()
}

func (client *HttpClient) request() (string, error) {
	client1 := &http.Client{}
	client.init()
	req, err := http.NewRequest(client.requestMothod, client.requestUrl, strings.NewReader(helper.JsonEncode(client.requestData)))
	if err != nil {
		return "", err
	}
	for key, value := range client.requestHeader {
		req.Header.Set(key, value.(string))
	}
	rep, err := client1.Do(req)
	data, err := ioutil.ReadAll(rep.Body)
	rep.Body.Close()
	if err != nil {
		return "", err
	}
	return string(data), nil
}

func (client *HttpClient) init() {
	if client.requestData == nil {
		client.requestData = make(map[string]interface{})
	}
	if client.requestHeader == nil {
		client.requestHeader = make(map[string]interface{})
	}
	if client.getParams == nil {
		client.getParams = make(map[string]string)
	}
}
